package com.bonc.ioc.demo.config;

import com.bonc.ioc.demo.condition.DecryptCondition;
import com.bonc.ioc.demo.condition.ProdActiveCondition;
import com.bonc.ioc.demo.condition.TestActiveCondition;
import com.bonc.ioc.demo.filter.CSRFilter;
import com.bonc.ioc.demo.filter.DecryptFilter;
import com.bonc.ioc.demo.filter.TestDecryptFilter;
import com.bonc.ioc.demo.filter.XssFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

/**
 * @projectName: sdvp
 * @description: 过滤器配置类
 * @author: Liyy
 * @create: 2020-08-21 15:45
 **/
@Configuration
public class FilterConfig {

    @Value("${websafe.referer}")
    private String referer;

    public static boolean testDecryptFilterFlag = false;

    /**
     * 注册跨站请求过滤器
     *
     * @return
     */
    @Bean
    @Conditional({DecryptCondition.class})
    public FilterRegistrationBean registCsrfFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new CSRFilter(referer));
        registration.addUrlPatterns("/*");
        registration.setName("CsrfFilter");
        registration.setOrder(1);
        return registration;
    }

    /**
     * 注册XSS防御、sql注入防御过滤器
     *
     * @return
     */
    @Bean
    @Conditional({DecryptCondition.class})
    public FilterRegistrationBean registXssFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new XssFilter());
        registration.addUrlPatterns("/*");
        registration.setName("XssFilter");
        registration.setOrder(2);
        return registration;
    }

    /**
     *
     * @return
     */
    @Bean
    @Conditional({ProdActiveCondition.class})
    public FilterRegistrationBean registDecryptFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new DecryptFilter());
        registration.addUrlPatterns("/*");
        registration.setName("DecryptFilter");
        registration.setOrder(3);
        return registration;
    }

    @Bean
    @Conditional({TestActiveCondition.class})
    public FilterRegistrationBean registTestDecryptFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new TestDecryptFilter());
        registration.addUrlPatterns("/*");
        registration.setName("TestDecryptFilter");
        registration.setOrder(4);
        testDecryptFilterFlag = true;
        return registration;
    }
}
